//
//  LSZVideoOfflineCacheVC.m
//  JKFuYinProject
//
//  Created by 九酷 on 2018/3/16.
//  Copyright © 2018年 LC. All rights reserved.
//

#import "LSZVideoOfflineCacheVC.h"
#import "LCVideoHomeListAboutModel.h"
#import "LSZVideoOfflineCacheVC+LCHomeBaiduAd.h"

@interface LSZVideoOfflineCacheVC ()

@end

@implementation LSZVideoOfflineCacheVC
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    [self getDataOfflineCache];
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}
- (void)dealloc
{
    NSLog(@"__func__dealloc = %s", __func__);
    [self baiduAdDealloc];
}
-(void)getDataOfflineCache
{
    self.arrayGetData = [[NSMutableArray alloc]init];
    if (self.isOkOffline == YES) {
        NSArray * arrayGetData = [[NSArray alloc]initWithContentsOfFile:[LSZSpecialPackaging saveTheNameOfVideo]];
        [self.arrayGetData addObjectsFromArray:arrayGetData];
        if (self.arrayGetData.count >0) {
             self.arrayGetData=(NSMutableArray *)[[self.arrayGetData reverseObjectEnumerator] allObjects];
            self.VideoOfflineManager = [[LSZOfflineVideoManager alloc]initWithOfflineVideo:self.arrayGetData];
            [self refreshTableView];
        }else{
            LSZEmptyDataVC * vc = [[LSZEmptyDataVC alloc]init];
            [vc showWithView:self.tableViewVideo];
            [self.tableViewVideo reloadData];
        }
    }else{
         NSArray * arrayGetData = [[NSArray alloc]initWithContentsOfFile:[LSZSpecialPackaging recordTheBrowsingHistoryVideo]];
        [self.arrayGetData addObjectsFromArray:arrayGetData];
        if (self.arrayGetData.count >0) {
            self.arrayGetData=(NSMutableArray *)[[self.arrayGetData reverseObjectEnumerator] allObjects];
            self.VideoOfflineManager = [[LSZOfflineVideoManager alloc]initWithOfflineVideo:self.arrayGetData];
            [self refreshTableView];
         }
        else{
            LSZEmptyDataVC * vc = [[LSZEmptyDataVC alloc]init];
            [vc showWithView:self.tableViewVideo];
            [self.tableViewVideo reloadData];
        }
    }
}
///增加广告
- (void)addBaiduAd {
    [self.arrayGetData insertObject:@{@"imageViewUrl" : @"",
                                           @"name" : @"",
                                           @"title" : @"",
                                           @"style" : @"-1",
                                           @"id_id" : @"0"} atIndex:arc4random_uniform((int)self.arrayGetData.count)];
    self.VideoOfflineManager = [[LSZOfflineVideoManager alloc]initWithOfflineVideo:self.arrayGetData];
}
//添加 数据 后 刷新界面显示数据
- (void)refreshTableView {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (self.adsArray.count > 0) {
            [self addBaiduAd];
            [self.tableViewVideo reloadData];
        }
    });
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
        [self.tableViewVideo reloadData];
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.arrayGetData = [[NSMutableArray alloc]init];
    if (self.isOkOffline == YES) {
        self.title = @"离线中心";
    }else{
        self.title = @"历史记录";
    }
    [self.tableViewVideo registerClass:[LSZVideoOfflineCacheTableViewCell class] forCellReuseIdentifier:@"LSZVideoOfflineCacheTableViewCell"];
    [self.tableViewVideo registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCellIdentifier"];
    UIButton *but = [UIButton buttonWithType:UIButtonTypeCustom];
    but.frame =CGRectMake(0,0, 60, 44);
    but.titleLabel.font = FONT_14;
    [but setTitle:@"全部删除" forState:UIControlStateNormal];
    [but addTarget:self action:@selector(popAllDelete) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem  *barBut = [[UIBarButtonItem alloc]initWithCustomView:but];
    self.navigationItem.rightBarButtonItem = barBut;
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.tabBarController.tabBar.translucent = NO;
    [self setupTableViewLayout];

    if (self.isOkOffline == NO) {
        [self pressToLoadAd];
    }
}
- (void)setupTableViewLayout
{
    [self.tableViewVideo mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.right.equalTo(self.view);
        if (@available(iOS 11, *)) {
            make.top.equalTo(self.view.mas_safeAreaLayoutGuideTop);
            make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom).offset(-0);
        }else{
            make.top.equalTo(self.view.mas_top);
            make.bottom.equalTo(self.view.mas_bottom).offset(-0);
        }
    }];
}

- (void)setupTableViewCompatibilityADLayout
{
    CGFloat width = MIN(self.view.width , self.view.height);
    [self.tableViewVideo mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.and.right.equalTo(self.view);
        if (@available(iOS 11, *)) {
            make.top.equalTo(self.view.mas_safeAreaLayoutGuideTop);
            make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom).offset(-width/20*3);
        }else{
            make.top.equalTo(self.view.mas_top);
            make.bottom.equalTo(self.view.mas_bottom).offset(-width/20*3);
        }
    }];
}

-(void)popAllDelete
{
    if (self.isOkOffline == YES) {
        [LSZSpecialPackaging clearCacheSpecificSuffixes:@"mp4"];
        [LSZSpecialPackaging clearCacheSpecificSuffixes:@"mp3"];
        [LSZSpecialPackaging deleteSomeSpecificFolders:@"Video.text"];
        [self setStringWarning:@"删除成功!"];
        [self getDataOfflineCache];
    }else{
        [LSZSpecialPackaging deleteSomeSpecificFolders:@"VideoBrowsingHistory.text"];
        [self setStringWarning:@"删除成功!"];
        [self.tableViewVideo reloadData];
        [self getDataOfflineCache];
    }
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.arrayGetData.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    LSZOfflineVideoMg * manager= nil;
    manager = self.VideoOfflineManager.arrayData[indexPath.row];

    if ([manager.style isEqualToString:@"-1"]) {
        UITableViewCell *cell;//去掉复用
        NSString *cellIdentifier = @"UITableViewCellIdentifier";
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        if (self.adViewArray.count > [manager.id_id integerValue])
        {
            BaiduMobAdNativeAdView *view = [self.adViewArray objectAtIndex:[manager.id_id integerValue]];
            [view removeFromSuperview];
            [cell addSubview:view];
            
            if (view.mainImageView.image != nil) {
                view.iconImageView.hidden = YES;
            }else{
                view.iconImageView.hidden = NO;
            }
            
            [self sendVisibleImpressionAtIndexPath:indexPath adIndex:[manager.id_id integerValue]];
        }
        return cell;
    }
    LSZVideoOfflineCacheTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"LSZVideoOfflineCacheTableViewCell" forIndexPath:indexPath];
    cell.videoManager = manager;
    cell.butDelete.tag = indexPath.row+1;
    [cell.butDelete addTarget:self action:@selector(clickDeleteRow:) forControlEvents:UIControlEventTouchUpInside];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
-(void)clickDeleteRow:(UIButton *)but
{
    LSZOfflineVideoMg * manager= nil;
    manager = self.VideoOfflineManager.arrayData[but.tag-1];
    if (self.isOkOffline == YES) {
        NSString * strName = [[NSString alloc]init];
        NSString * stringName = [[NSString alloc]init];//不带后缀
        NSString * str1 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES)[0];
        if([manager.style isEqualToString:@"1"]||[manager.style isEqualToString:@"3"]){
            strName = [str1 stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mp4",manager.title]];
            stringName = NSStr(manager.title);
            [self DeleteByPath:strName :stringName :manager.style];
        }
        if ([manager.style isEqualToString:@"2"]||[manager.style isEqualToString:@"3"]) {
            strName = [str1 stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mp3",manager.title]];
            stringName = NSStr(manager.title);
            [self DeleteByPath:strName :stringName :@"2"];
        }
        [self getDataOfflineCache];
    }else{
        [self deleteDataFromVideoHistory:NSStr(manager.id_id)];
        [self setStringWarning:@"删除成功!"];
        [self getDataOfflineCache];
    }
}
-(void)DeleteByPath :(NSString *)str :(NSString *)stringName :(NSString *)value
{
    NSFileManager* fileManager=[NSFileManager defaultManager];
    BOOL blHave=[[NSFileManager defaultManager] fileExistsAtPath:str];
    if (!blHave) {
        //视频有问题 删除文件m
        [self deleteTheRecordedData:stringName];
        [self setStringWarning:@"删除成功!"];
        return ;
    }else {
        //存在
        BOOL blDele= [fileManager removeItemAtPath:str error:nil];
         if (blDele) {
             [self deleteTheRecordedData:stringName];
             if (![value isEqualToString:@"3"]) {
                 [self setStringWarning:@"删除成功!"];
             }
        }else {
            [self setStringWarning:@"删除失败!"];
         }
    }
}
#pragma mark - 删除video里面的数据
-(void)deleteTheRecordedData :(NSString *)str
{
    NSMutableArray * arrayMove = [[NSMutableArray alloc]initWithArray:self.arrayGetData];
    for (int i = 0; i<self.arrayGetData.count; i++) {
        NSDictionary * dic = self.arrayGetData[i];
        NSString * title = NSStr(dic[@"title"]);
        if ([title isEqualToString:str]) {
            [arrayMove removeObjectAtIndex:i];
        }
    }
    [arrayMove writeToFile:[LSZSpecialPackaging saveTheNameOfVideo] atomically:YES];
}
#pragma mark- 删除视频历史记录里面的数据
-(void)deleteDataFromVideoHistory :(NSString *)str
{
    NSMutableArray * arrayMove = [[NSMutableArray alloc]initWithArray:self.arrayGetData];
    for (int i = 0; i<self.arrayGetData.count; i++) {
        NSDictionary * dic = self.arrayGetData[i];
        NSString * title = NSStr(dic[@"id_id"]);
        if ([title isEqualToString:str]) {
            [arrayMove removeObjectAtIndex:i];
        }
    }
    [arrayMove writeToFile:[LSZSpecialPackaging recordTheBrowsingHistoryVideo] atomically:YES];
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    LSZOfflineVideoMg * manager= nil;
    manager = self.VideoOfflineManager.arrayData[indexPath.row];
    if ([manager.style isEqualToString:@"-1"]) {
        return;
    }
    if(self.isOkOffline == YES){
        NSString * str = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES)[0];
        LSZVideoPlaybackViewController * VC = [[LSZVideoPlaybackViewController alloc]init];
        VC.playUrl = [str stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mp4",manager.title]];
        VC.titleString = manager.title;
        VC.isOffline = YES;
        [self.navigationController pushViewController:VC animated:YES];
    }else{
//历史记录 跳到视频的详情页
        LCVideoDetailChangeHeaderController *viewController = [[LCVideoDetailChangeHeaderController alloc] init];
        LCVideoHomeListAboutModel *listAboutModel = [[LCVideoHomeListAboutModel alloc] init];
        listAboutModel.id =  manager.id_id;
        listAboutModel.name =  manager.title;
        listAboutModel.pic =  manager.imageViewUrl;
        listAboutModel.author =  manager.name;
        viewController.listAboutModel = listAboutModel;
        [self.navigationController pushViewController:viewController animated:YES];
    }
}
-(UITableView *)tableViewVideo
{
    if (_tableViewVideo == nil) {
        _tableViewVideo = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight) style:UITableViewStylePlain];
        _tableViewVideo.delegate = self;
        _tableViewVideo.dataSource = self;
        _tableViewVideo.estimatedRowHeight = 0;
        _tableViewVideo.estimatedSectionHeaderHeight = 0;
        _tableViewVideo.estimatedSectionFooterHeight = 0;
        _tableViewVideo.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
        [self.view addSubview:_tableViewVideo];
    }
    return _tableViewVideo;
}
@end
